package com.neusoft.neuiotms.dcam.fixed.service.impl;

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.converter.ContractItemConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.ContractItemDTO;
import com.neusoft.neuiotms.dcam.fixed.model.ContractItem;
import com.neusoft.neuiotms.dcam.fixed.repository.ContractItemRepository;
import com.neusoft.neuiotms.dcam.fixed.service.ContractItemService;

@Service
public class ContractItemServiceImpl implements ContractItemService {

    @Autowired
    private ContractItemRepository contractItemRepository;
    @Autowired
    private ContractItemConverter contractItemConverter;

    @Override
    public List<ContractItemDTO> findAll(final Searchable searchable) {
        final List<ContractItem> models = this.contractItemRepository.index(searchable);
        final List<ContractItemDTO> dtos = this.contractItemConverter.toListDTO(models);
        return dtos;
    }

    @Override
    public Page<ContractItemDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<ContractItem> models = this.contractItemRepository.search(pageable, searchable);
        return this.contractItemConverter.toPageDTO(models);
    }

    @Override
    public ContractItemDTO create(final ContractItemDTO dto) {

        final ContractItem model = this.contractItemConverter.toModel(dto);
        this.contractItemRepository.save(model);
        return this.contractItemConverter.toDTO(model);
    }

    @Override
    public ContractItemDTO details(final Long id) {

        ContractItem model;
        try {
            model = this.contractItemRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.contractItemConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        this.contractItemRepository.deleteById(id);
    }

    @Override
    public ContractItemDTO update(final Long id, final ContractItemDTO dto) {

        ContractItem model;
        try {
            model = this.contractItemRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.contractItemConverter.toModel(dto);
        this.contractItemRepository.save(model);
        return this.contractItemConverter.toDTO(model);
    }

}
